#!/bin/bash
set -e
export PUPPETEER_SKIP_DOWNLOAD=true

TOOL=$1

if [ -z "$TOOL" ]; then
  echo "❌ 请输入要使用的包管理工具，例如：bash init-git-hooks.sh pnpm"
  exit 1
fi

INSTALL_CMD=""
ADD_CMD=""
case $TOOL in
npm)
  INSTALL_CMD="npm install git+ssh://git@gitee.com:getbetter/git-hooks-config.git -D"
  ADD_CMD="npm install -D"
  ;;
yarn)
  INSTALL_CMD="yarn add git+ssh://git@gitee.com:getbetter/git-hooks-config.git -D"
  ADD_CMD="yarn add -D"
  ;;
pnpm)
  INSTALL_CMD="pnpm add git+ssh://git@gitee.com:getbetter/git-hooks-config.git -D"
  ADD_CMD="pnpm add -D"
  ;;
*)
  echo "❌ 不支持的包管理工具: $TOOL"
  exit 1
  ;;
esac

echo "🔧 使用 $TOOL 安装 git-hooks-config 包..."
eval "$INSTALL_CMD"

echo "📦 动态解析 git-hooks-config 中的 devDependencies 并安装到主项目中..."
PKG_PATH="node_modules/git-hooks-config/package.json"

if [ ! -f "$PKG_PATH" ]; then
  echo "❌ 未找到 package.json: $PKG_PATH"
  exit 1
fi

DEPS=$(node -e "const deps=require('./$PKG_PATH').devDependencies; console.log(Object.entries(deps).map(([k,v])=>k+'@'+v).join(' '))")

if [ -z "$DEPS" ]; then
  echo "⚠️  未发现依赖需要安装"
else
  echo "➡️  安装依赖: $DEPS"
  eval "$ADD_CMD $DEPS"
fi

echo "✅ 安装 husky..."
if [ -d ".husky" ]; then
  echo "🔄 检测到已有 .husky 目录，正在删除..."
  rm -rf .husky
fi
npx husky init

echo "📂 拷贝 hooks 和配置文件到当前项目..."
cp -r node_modules/git-hooks-config/.husky/* .husky/
cp node_modules/git-hooks-config/commitlint.config.js commitlint.config.js
cp node_modules/git-hooks-config/header-pattern.cjs header-pattern.cjs

case $TOOL in
npm)
  REMOVE_CMD="npm uninstall git-hooks-config"
  ;;
yarn)
  REMOVE_CMD="yarn remove git-hooks-config"
  ;;
pnpm)
  REMOVE_CMD="pnpm remove git-hooks-config"
  ;;
*)
  echo "❌ 不支持的包管理工具: $TOOL"
  exit 1
  ;;
esac

eval "$REMOVE_CMD"
echo "🎉 Git Hooks 配置完成"
